<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width=650
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
  >
    <a-form>
      <a-form-item label='所拥有的权限'>
        <a-tree
          checkable
          :treeData="treeData"
          :replaceFields="{children:'children', title:'title', key:'id'}"
          :checkStrictly="checkStrictly"
          :expandedKeys="expandedKeys"
          :checkedKeys="checkedKeys"
          :selectedKeys="selectedKeys"
          @expand="onExpand"
          @check="onCheck"
          @select="onTreeNodeSelect"
        >
          <span slot="hasDatarule" slot-scope="{slotTitle,ruleFlag}">
            {{ slotTitle }}
            <a-icon v-if="ruleFlag" type="align-left" style="margin-left:5px;color: red;"></a-icon>
          </span>
        </a-tree>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </div>

    <!-- <role-datarule-modal ref="datarule"></role-datarule-modal> -->

  </a-drawer>

</template>
<script>
import { queryTreeListForRole, queryRolePermission, saveRolePermission } from '@/services/system'
import { Tree as ATree } from 'ant-design-vue'
export default {
  name: 'PerssionModal',
  components: {
    ATree
  },
  data() {
    return {
      roleId: '',
      treeData: [],
      defaultCheckedKeys: [],
      defaultCheckedObj: {},
      checkedKeys: [],
      expandedKeys: [],
      allTreeKeys: [],
      autoExpandParent: true,
      checkStrictly: true,
      title: '角色权限配置',
      visible: false,
      loading: false,
      selectedKeys: [],
      treeListData: []
    }
  },
  methods: {
    onTreeNodeSelect() {
      // if(id && id.length>0){
      //   this.selectedKeys = id
      // }
      // this.$refs.datarule.show(this.selectedKeys[0],this.roleId)
    },
    onCheck(o) {
      if (this.checkStrictly) {
        this.checkedKeys = o.checked
      } else {
        this.checkedKeys = o
      }
    },
    show(roleId) {
      this.roleId = roleId
      this.visible = true
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    reset() {
      this.expandedKeys = []
      this.checkedKeys = []
      this.defaultCheckedObj = {}
      this.defaultCheckedKeys = []
      this.loading = false
    },
    expandAll() {
      console.log(this.allTreeKeys)
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v === 1) {
        this.checkStrictly = false
      } else if (v === 2) {
        this.checkStrictly = true
      }
    },
    handleCancel() {
      this.close()
    },
    handleSubmit(exit) {
      // let params =  {
      //   roleId:this.roleId,
      //   permissionIds:this.checkedKeys.join(","),
      //   lastpermissionIds:this.defaultCheckedKeys.join(","),
      // };
      const formData = []
      // 检查脏数据
      this.checkedKeys.forEach(item => {
        const data = {
          resourceType: 'URL',
          crudType: this.defaultCheckedObj[item] ? 'UPDATE' : 'SAVE',
          resourceId: item,
          roleId: this.roleId,
          id: this.defaultCheckedObj[item] && this.defaultCheckedObj[item].id
        }
        formData.push(data)
      })
      Object.keys(this.defaultCheckedObj).forEach(key => {
        if (!this.checkedKeys.includes(key)) {
          const item = this.defaultCheckedObj[key]
          const data = {
            resourceType: 'URL',
            crudType: 'DELETE',
            resourceId: item.resourceId,
            roleId: item.roleId,
            id: item.id
          }
          formData.push(data)
        }
      })
      this.loading = true
      saveRolePermission(formData).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loading = false
          if (exit) {
            this.close()
          }
        } else {
          this.$message.error(res.message)
          this.loading = false
          if (exit) {
            this.close()
          }
        }
        this.loadData()
      }).finally(() => {
        this.loading = false
      })
    },
    loadData() {
      queryTreeListForRole().then((res) => {
        this.treeData = res.result
        this.allTreeKeys = []
        this.getAllTreeKeys(res.result)
        this.expandedKeys = this.allTreeKeys
      })
      queryRolePermission({ roleId: this.roleId }).then((res) => {
        if (res.success) {
          this.checkedKeys = []
          this.treeListData = []
          this.defaultCheckedObj = {}
          res.result.forEach(item => {
            this.checkedKeys.push(item.resourceId)
            this.defaultCheckedObj[item.resourceId] = item
          })
          // this.checkedKeys = [...res.result]
          this.defaultCheckedKeys = [...this.checkedKeys]
        }
      })
    },
    getAllTreeKeys(tree) {
      tree.forEach(item => {
        this.allTreeKeys.push(item.id)
        if (item.children && item.children.length > 0) {
          this.getAllTreeKeys(item.children)
          this.treeListData.push({ ...item })
        }
      })
    }
  },
  watch: {
    visible() {
      if (this.visible) {
        this.loadData()
      }
    }
  }
}

</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

</style>
